package com.atguigu.gmall.gateway.filter;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Component
public class GlobalLoginFilter implements GlobalFilter , Ordered {

    @Autowired
    RedisTemplate redisTemplate;

    @Value("${auth.url}")
    private String[] authUrl;

    private static final String LOGINURL = "http://passport.gmall.com/login.html?originUrl=";

    private static final String TOKEN = "token";

    //配置URI路径
    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //当前路径
        String path = request.getURI().getPath();
        //内部资源，web无权访问
        if (antPathMatcher.match("/**/inner/**",path)){
            return getVoidMono(response,ResultCodeEnum.PERMISSION);
        }

        //登录
        //异步
        String userId = getUserId(request);
        if (antPathMatcher.match("/**/auth/**",path)){
            if (StringUtils.isEmpty(userId)){
                return getVoidMono(response,ResultCodeEnum.LOGIN_AUTH);
            }
        }

        //同步
        for (String url : authUrl) {
            if (path.indexOf(url) != -1 && StringUtils.isEmpty(userId)) {
                response.setStatusCode(HttpStatus.SEE_OTHER);
                try {
                    response.getHeaders().set(HttpHeaders.LOCATION,LOGINURL+ URLEncoder.encode(request.getURI().toString(),"utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return response.setComplete();
            }
        }

        if (!StringUtils.isEmpty(userId)) {
            request.mutate().header("userId",userId);
        }
        String userTempId = getUserTempId(request);
        if (!StringUtils.isEmpty(userTempId)){
            request.mutate().header("userTempId",userTempId);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    //校验用户是否登录
    private String getUserId(ServerHttpRequest request){
        String token = request.getHeaders().getFirst(TOKEN);
        //获取token
        if (StringUtils.isEmpty(token)){
            HttpCookie cookie = request.getCookies().getFirst(TOKEN);
            if (cookie != null){
                token = cookie.getValue();
            }
        }
        if (!StringUtils.isEmpty(token)){
            if (redisTemplate.hasKey(token)){
                return (String) redisTemplate.opsForValue().get(token);
            }
        }
        return null;
    }

    private Mono<Void> getVoidMono(ServerHttpResponse response, ResultCodeEnum resultCodeEnum){
        Result<Object> build = Result.build(null, resultCodeEnum);
        String result = JSONObject.toJSONString(build);
        DataBuffer wrap = response.bufferFactory().wrap(result.getBytes());
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        return response.writeWith(Mono.just(wrap));
    }

    private String getUserTempId(ServerHttpRequest request){
        String userTempId = request.getHeaders().getFirst("userTempId");
        if (StringUtils.isEmpty(userTempId)) {
            HttpCookie httpCookie = request.getCookies().getFirst("userTempId");
            if (httpCookie != null){
                userTempId = httpCookie.getValue();
            }
        }
        return userTempId;
    }
}
